package com.tender.integration.websocket.converter;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.tender.constants.Constants;
import com.tender.enums.ErrorTypeEnum;
import com.tender.exceptions.WebSocketException;
import com.tender.integration.websocket.pojo.WebSocketWrapperInfo;
import com.tender.utils.LoginUser;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class WebSocketConverter {

    /**
     * ctrl + alt + M 快捷键
     */
    public static WebSocketWrapperInfo prepareWebSocketInfo(String port, WebSocketSession session, LoginUser userInfo) {
        WebSocketWrapperInfo webSocketWrapperInfo = new WebSocketWrapperInfo();
        webSocketWrapperInfo.setWebSocketSession(new ConcurrentWebSocketSessionDecorator(session, Constants.SEND_TIME_LIMIT, Constants.BUFFER_SIZE_LIMIT));
        // 根据token获取用户信息
        webSocketWrapperInfo.setUserId(userInfo.getUserId());
        webSocketWrapperInfo.setDevice(userInfo.getDevice());
        webSocketWrapperInfo.setUuid(IdUtil.simpleUUID());
        try {
            webSocketWrapperInfo.setAddress(InetAddress.getLocalHost().getHostAddress() + ":" + (StrUtil.isBlank(port) ? "8080" : port));
        } catch (UnknownHostException e) {
            // TODO 抛异常?
            throw new WebSocketException(ErrorTypeEnum.WEB_SOCKET_PARSE_HOST_INFO_EXP);
        }
        return webSocketWrapperInfo;
    }

}
